#!/bin/bash

#########################################################################################
#
#  Copyright (c) 2015 arakasi72 (https://github.com/arakasi72)
#
#  Modified by Aniverse
#
#  --> Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
#
#########################################################################################

###############################
### SET VARIABLES ###
###############################

PATH=/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/bin:/sbin

#url's of the major components
rt_url="http://rtorrent.net/downloads/"

xmlrpc_url="https://svn.code.sf.net/p/xmlrpc-c/code/stable/"
xmlrpc_url_alt="https://github.com/mirror/xmlrpc-c"

ru_url="https://github.com/Novik/ruTorrent/"
adl_url="https://github.com/autodl-community/"

if [ $(dpkg-query -W -f='${Status}' lsb-release 2>/dev/null | grep -c "ok installed") -eq 0 ]; then
echo "Installing lsb-release"
apt-get -yqq install lsb-release 2>&1 >> /dev/null
fi

fullrel=$(lsb_release -sd)
osname=$(lsb_release -si)
relno=$(lsb_release -sr | cut -d. -f1)

phpver=php5
phploc=/etc/php5
geoipver=php5-geoip
libcver=libcurl3

if [ "$relno" = "16" ] || [ "$relno" = "17" ] || [ "$relno" = "9" ]; then
  phpver=php7.0
  phploc=/etc/php/7.0
  geoipver=php-geoip
fi

if [ $(lsb_release -sr) = "17.10" ]; then
  phpver=php7.1
  phploc=/etc/php/7.1
  geoipver=php-geoip
fi

if [ "$relno" = "18" ]; then
  phpver=php7.2
  phploc=/etc/php/7.2
  geoipver=php-geoip
  libcver=libcurl4
fi

function isValidIpAddress() { echo $1 | grep -qE '^[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?$' ; }
function isInternalIpAddress() { echo $1 | grep -qE '(192\.168\.((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.((\d{1,2})$|(1\d{2})$|(2[0-4]\d)$|(25[0-5])$))|(172\.((1[6-9])|(2\d)|(3[0-1]))\.((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.((\d{1,2})$|(1\d{2})$|(2[0-4]\d)$|(25[0-5])$))|(10\.((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.((\d{1,2})$|(1\d{2})$|(2[0-4]\d)$|(25[0-5])$))' ; }

export serverip=$(ip route get 8.8.8.8 | awk 'NR==1 {print $7}')
export serverdn=$(perl -MSocket -le "print((gethostbyaddr(inet_aton('$serverip'), AF_INET))[0])")
isInternalIpAddress "$serverip" || export serverip=$( wget --no-check-certificate -t1 -T6 -qO- v4.ipv6-test.com/api/myip.php )
isValidIpAddress "$serverip" || export serverip=$( wget --no-check-certificate -t1 -T6 -qO- checkip.dyndns.org | sed -e 's/.*Current IP Address: //' -e 's/<.*$//' )
isValidIpAddress "$serverip" || export serverip=$( wget --no-check-certificate -t1 -T7 -qO- ipecho.net/plain )
isValidIpAddress "$serverip" || { echo "Failed to detect your public IPv4 address, use internal address instead" ; export serverip=$(ip route get 8.8.8.8 | awk 'NR==1 {print $NF}') ; }

# This may be an internal IP, but it doesn't matter
#export serverip=$(ip route get 8.8.8.8 | awk 'NR==1 {print $NF}')
export logfile="/dev/null"
webpass=''
cronline1="@reboot sleep 10; /usr/local/bin/rtcheck irssi rtorrent"
cronline2="*/10 * * * * /usr/local/bin/rtcheck irssi rtorrent"
dlflag=1
ssh_port_default=1
ftp_port_default=1

skip_rt=1
sshport=''
rudevflag=1
rurelease=master
passfile='/etc/nginx/.htpasswd'
package_list="sudo nano autoconf build-essential ca-certificates comerr-dev curl cfv dtach htop irssi libcloog-ppl-dev libcppunit-dev $libcver libncurses5-dev libterm-readline-gnu-perl libsigc++-2.0-dev libperl-dev libtool libxml2-dev ncurses-base ncurses-term ntp patch pkg-config $phpver-fpm $phpver $phpver-cli $phpver-dev $phpver-curl $geoipver $phpver-mcrypt $phpver-xmlrpc python-scgi screen subversion texinfo unzip zlib1g-dev libcurl4-openssl-dev mediainfo software-properties-common aptitude $phpver-json nginx-full apache2-utils git libarchive-zip-perl libnet-ssleay-perl libhtml-parser-perl libxml-libxml-perl libjson-perl libjson-xs-perl libxml-libxslt-perl libjson-rpc-perl libarchive-zip-perl"
Install_list=""
unixpass=""
passflag=0
forceyes=1
selfsign=1
rut_add_users=1
rtorrentrel=''
enable_ipv6=1

###############################
### FUNCTIONS ###
###############################

#function to check if a web site is reachable
check_url() {
  if [[ `wget -S --spider $1  2>&1 | grep 'HTTP/1.1 200 OK'` ]]; then return 0; else return 1; fi
}

# checks if an application is installed
installed() {
hash $1 2>/dev/null
}

#function to check if string is valid format for an ip address
valid_ip()
{
local ip=${1:-1.2.3.4}
local i
if expr "$ip" : '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$' >/dev/null; then
  for i in 1 2 3 4; do
    if [ $(echo "$ip" | cut -d. -f$i) -gt 255 ]; then
      return 1
    fi
  done
  return 0
else
  return 1
fi
}

#function to generate random password
genpasswd() {
local genln=$1
[ -z "$genln" ] && genln=8
tr -dc A-Za-z0-9 < /dev/urandom | head -c ${genln} | xargs
}

#function executed if the script finishes early
early_exit() {
echo "Installation is incomplete. Run rtinst again to complete"
echo
if hash rtorrent >> /dev/null 2>&1; then
  rt_current=$(rtorrent -h | grep -om 1 "[0-9]\{1,2\}\.[0-9]\{1,2\}\.[0-9]\{1,2\}")
  echo "rtorrent $rt_current installed"
else
  echo "rtorrent was not installed"
fi
echo
echo "FTP Port set to $ftpport"
echo
echo "IMPORTANT - SSH Port has been set to: $sshport"
echo "IMPORTANT - SSH Port has been set to: $sshport"
echo "IMPORTANT - SSH Port has been set to: $sshport"
exit 1
}

#function to set a user input password
set_pass() {
local localpass
local exitvalue=0
local password1
local password2

exec 3>&1 >/dev/tty

echo "Enter a password (6+ chars)"
echo "or leave blank to generate a random one"

while [ -z $localpass ]
do
  echo "Please enter the new password:"
  stty -echo
  read password1
  stty echo

# check that password is valid
  if [ -z $password1 ]; then
    echo "Random password generated, will be provided to user at end of script"
    exitvalue=1
    localpass=$(genpasswd)
  elif [ ${#password1} -lt 6 ]; then
    echo "password needs to be at least 6 chars long" && continue
  else
    echo "Enter the new password again:"
    stty -echo
    read password2
    stty echo

# Check both passwords match
    if [ $password1 != $password2 ]; then
      echo "Passwords do not match"
    else
      localpass=$password1
    fi
  fi
done

exec >&3-
echo $localpass
return $exitvalue
}

#function to determine random number between 2 numbers
random()
{
    local min=$1
    local max=$2
    local RAND=`od -t uI -N 4 /dev/urandom | awk '{print $2}'`
    RAND=$((RAND%((($max-$min)+1))+$min))
    echo $RAND
}

# function to ask user for y/n response
ask_user(){
local answer
while true
  do
    read answer
    case $answer in [Yy]* ) return 0 ;;
                    [Nn]* ) return 1 ;;
                        * ) echo "Enter y or n";;
    esac
  done
}

# function to enter IP address
enter_ip() {
while true
  do
    if valid_ip $serverip ; then
      echo "Your Server IP is $serverip"
      echo -n "Is this correct y/n? "
      ask_user && return 0
    else
      echo "Invalid IP address, please try again"
    fi

    echo "enter your server's IP address"
    echo "e.g. 213.0.113.113"
    read serverip
  done
}

###############################
### INITIAL SYSTEM CHECKS ###
###############################

#check it is being run as root
if [ "$(id -u)" != "0" ]; then
  echo "Must be run from root or using sudo" && exit 1
fi

# determine system
if ([ "$osname" = "Ubuntu" ] && [ $relno -ge 14 ]) || ([ "$osname" = "Debian" ] && [ $relno -ge 8 ])  || ([ "$osname" = "Raspbian" ] && [ $relno -ge 8 ]); then
  echo $fullrel
else
 echo $fullrel
 echo "Only Ubuntu release 14 and later, and Debian and Raspbian release 8 and later, are supported"
 echo "Your system does not appear to be supported"
 echo "Check https://github.com/arakasi72/rtinst/wiki/Installing-on-Older-OS to see if it is supported by an earlier rtinst release"
 exit
fi

# get options
OPTS=$(getopt -n "$0" -o dltfrmysiu:p:w:v: --long "dload,log,ssh-default,ftp-default,rutorrent-stable,rutorrent-master,force-yes,self-signed,enable-ipv6,user:,password:,webpass:,version:" -- "$@")

eval set -- "$OPTS"

while true; do
  case "$1" in
    -d | --dload ) dlflag=0; shift ;;
    -l | --log ) logfile="$HOME/rtinst.log"; shift ;;
    -t | --ssh-default ) ssh_port_default=0; shift;;
    -f | --ftp-default ) ftp_port_default=0; shift;;
    -r | --rutorrent-stable ) rudevflag=1; shift;;
    -m | --rutorrent-master ) rudevflag=0; shift;;
    -y | --force-yes ) forceyes=0; shift;;
    -s | --self-signed ) selfsign=0; shift;;
    -i | --enable-ipv6 ) enable_ipv6=0; shift;;
    -u | --user ) user="$2"; shift; shift;;
    -p | --password ) unixpass="$2"; shift; shift;;
    -w | --webpass ) webpass="$2"; shift; shift;;
    -v | --version ) rtorrentrel="$2"; shift; shift;;
    -- ) shift; break ;;
     * ) break ;;
  esac
done

# Check if there is more than 0 argument
if [ $# -gt 0 ]; then
  echo "No arguments allowed $1 is not a valid argument"
  exit 1
fi

# check required web repos are accessible
os_repo=0
major_repo=0

sed  -i "s/\/debian\s/\/debian\/ /g" /etc/apt/sources.list

echo
echo "Checking the web sites we will need are accessible"
echo  "Checking $osname mirrors"
for i in $(cat /etc/apt/sources.list | grep "^deb http" | cut -d' ' -f2 | uniq ); do
  echo -n $i": "
  check_url $i && echo "OK" || { echo "FAIL"; os_repo=1; }
done

echo
echo "Checking major 3rd party components"
echo -n "Rtorrent: "; check_url $rt_url && echo "OK" || { echo "FAIL"; major_repo=1; }

echo -n "xmlrpc-c: "; check_url $xmlrpc_url && echo "OK" ||  xmlrpc_repo=1

if [[ $xmlrpc_repo = 1 ]]; then
  xmlrpc_url=$xmlrpc_url_alt
  check_url $xmlrpc_url && echo "OK" || { echo "FAIL"; major_repo=1; }
fi

echo -n "RuTorrent: ";check_url $ru_url && echo "OK" || { echo "FAIL"; major_repo=1; }
echo -n "Autodl-irssi: "; check_url $adl_url && echo "OK" || { echo "FAIL"; major_repo=1; }

if [ $os_repo = 1 ]; then
  echo "Some of your $osname mirrors are down, try again later"
  exit 1
fi

if [ $major_repo = 1 ]; then
  echo "Some of the repositories we need are not currently available."
  echo "We will continue for now, but may not be able to finish"
  echo "You can rerun rtinst later to complete the installation if needed"
fi
echo

# check IP Address
[ $forceyes = 1 ] && enter_ip

echo "Your server's IP is set to $serverip"


if [ -z "$serverdn" ]; then
  echo "Unable to determine domain"
else
  echo "Your domain is set to $serverdn"
fi

#check rtorrent installation
if installed rtorrent; then
  rt_current=$(rtorrent -h | grep -om 1 "[0-9]\{1,2\}\.[0-9]\{1,2\}\.[0-9]\{1,2\}")
  if [ $forceyes = 1 ]; then
    echo "rtorrent $rt_current has been detected."
    echo -n "Do you wish to skip rtorrent compilation? "
    if ask_user; then
      skip_rt=0
      echo "rtorrent installation will be skipped."
    else
      skip_rt=1
      echo "rtorrent will be re-installed"
    fi
  else
    skip_rt=0
    echo "rtorrent $rt_current has been detected."
    echo "rtorrent installation will be skipped."
  fi
fi

###############################
### PREPARE SYSTEM ###
###############################

# set and prepare user
if [ -z "$user" ]; then
  if [ "$SUDO_USER" = "root" ] || [ -z "$SUDO_USER" ]; then
    echo "Enter the name of the user to install to"
    echo "This will be your primary user"
    echo "It can be an existing user or a new user"
    echo

    confirm_name=1
    while [ $confirm_name = 1 ]
      do
        read -p "Enter user name: " answer
        addname=$answer
        echo -n "Confirm that user name is $answer y/n? "
        if ask_user; then
          confirm_name=0
        fi
      done

    user=$addname

  else
    user=$SUDO_USER
  fi
fi

# Lower case
user=`  echo $user | tr 'A-Z' 'a-z'  `

if id -u $user >/dev/null 2>&1; then
  echo "$user already exists"
else
  if [ -z "$unixpass" ]; then
    adduser --force-badname --gecos "" $user
  else
    adduser --force-badname --gecos "" $user --disabled-password
    echo "$user:$unixpass" | sudo chpasswd
  fi
fi

home=$(eval echo "~$user")

#set password for rutorrent
if [ -z "$webpass" ] && [ $forceyes = 0 ]; then
  if [ -z $(grep -s $user $passfile) ]; then
    webpass=$(genpasswd)
    passflag=1
  else
    passflag=2
  fi
fi



if [ -z "$webpass" ]  && [ $passflag != 2 ]; then
  if [ ! -z $(grep -s $user $passfile) ]; then
    echo "There is an existing RuTorrent password for $user"
    echo -n "Use existing password y/n ? "
    if ask_user; then
      passflag=2
    fi
  fi
  
  if [ $passflag != 2 ]; then
    echo "Set Password for RuTorrent web client"
    webpass=$(set_pass)
    passflag=$?
  fi
fi

rut_user_list=$(ls /var/www/rutorrent/conf/users 2>/dev/null | sed "s/$user//g")

for rut_user in $rut_user_list; do
  if ! id -u $rut_user >/dev/null 2>&1; then
    rut_user_list=$(echo $rut_user_list | sed "s/$rut_user//g")
  fi
done

if [ -z "$rut_user_list" ]; then
  echo "No additional users to add"
else
  echo "These users have been detected:"
  for rut_user in $rut_user_list; do
    echo $rut_user
  done

  if [ $forceyes = 0 ]; then
    echo "Users will be added"
    rut_add_users=0
  else
    echo -n "Add them to rutorrent y/n ? "
    if ask_user; then
      rut_add_users=0
    fi
  fi
fi

#Interaction ended message
echo
echo "No more user input required, you can complete unattended"
echo "It will take approx 10 minutes for the script to complete"
echo

#update amd upgrade system
echo "Updating package lists" | tee $logfile
apt-get -qq update | tee -a $logfile

echo "Upgrading packages" | tee -a $logfile
export DEBIAN_FRONTEND=noninteractive
apt-get -qq upgrade >> $logfile 2>&1
if ! [ $? = 0 ]; then
  echo "Problem upgrading packages. Run 'apt-get upgrade' successfully and rerun the script" && exit
fi

apt-get clean && apt-get autoclean >> $logfile 2>&1

#install the packsges needed
echo "Installing required packages" | tee -a $logfile
for package_name in $package_list
  do
    if [ $(apt-cache show -q=0 $package_name 2>&1 | grep -c "No packages found") -eq 0 ]; then
      if [ $(dpkg-query -W -f='${Status}' $package_name 2>/dev/null | grep -c "ok installed") -eq 0 ]; then
        install_list="$install_list $package_name"
      fi
    else
      echo $package_name" not found, skipping"
    fi
  done

test -z "$install_list" || apt-get -qq install $install_list >> $logfile 2>&1
if ! [ $? = 0 ]; then
  echo "Problem installing packages. Check log and rerun once it is resolved" && exit
fi

if [[ $phpver =~ php7.[0-9] ]]; then
  apt-get -qq install $phpver-mbstring >> $logfile 2>&1
fi

#install unrar package
if ! installed unrar; then
    echo "Installing rar/unrar"
    cd /root
    if [ "$(uname -m)" = "x86_64" ]; then
        wget https://github.com/Aniverse/BitTorrentClientCollection/raw/master/Other%20Tools/rarlinux-x64-5.6.1.tar.gz >> $logfile 2>&1
        tar xvzf rarlinux-x64-5.6.1.tar.gz >> $logfile 2>&1
        rm rarlinux-x64-5.6.1.tar.gz
    elif [ "$(uname -m)" = "x86_32" ]; then
        wget https://github.com/Aniverse/BitTorrentClientCollection/raw/master/Other%20Tools/rarlinux-5.6.1.tar.gz >> $logfile 2>&1
        tar xvzf rarlinux-5.6.1.tar.gz >> $logfile 2>&1
        rm rarlinux-5.6.1.tar.gz
    fi
    cp -f /root/rar/rar /bin/rar
    cp -f /root/rar/unrar /bin/unrar
    rm -r /root/rar
fi

if installed unrar; then
    echo "rar/unrar installed"
else
    echo "rar/unrar install failed"
fi

#install ffmpeg
echo "Installing ffmpeg" ; cd
if [ "$(uname -m)" = "x86_64" ]; then
    wget https://github.com/Aniverse/BitTorrentClientCollection/raw/master/Other%20Tools/ffmpeg-4.0.2-64bit-static.tar.xz >> $logfile 2>&1
    tar xf ffmpeg-4.0.2-64bit-static.tar.xz
elif [ "$(uname -m)" = "x86_32" ]; then
    wget https://github.com/Aniverse/BitTorrentClientCollection/raw/master/Other%20Tools/ffmpeg-3.4.2-32bit-static.tar.xz >> $logfile 2>&1
    tar xf ffmpeg-3.4.2-32bit-static.tar.xz
fi
rm -rf ffmpeg-*bit-static/{manpages,presets,model,readme.txt,GPLv3.txt}
cp ffmpeg-*bit-static/* /usr/local/bin
chmod 755 /usr/local/bin/{ffmpeg,ffprobe,ffmpeg-10bit,qt-faststart}
rm -rf ffmpeg-*bit-static*

echo "Completed installation of required packages        "

#add user to sudo group if not already
if groups $user | grep -q -E ' sudo(\s|$)'; then
  echo "$user already has sudo privileges"
else
  adduser $user sudo
fi

cd $home

#raise file limits
sed -i '/hard nofile/ d' /etc/security/limits.conf
sed -i '/soft nofile/ d' /etc/security/limits.conf
sed -i '$ i\* hard nofile 666666\n* soft nofile 666666' /etc/security/limits.conf


###############################
### CONFIGURE SSH ###
###############################

echo "Configuring SSH" | tee -a $logfile

oldsshport=$(grep -P '^[#\s]*Port ' /etc/ssh/sshd_config | sed 's/[^0-9]*//g')

if [ "$ssh_port_default" = "0" ]; then
  sshport=$oldsshport
elif [ "$oldsshport" = "22" ] && [ "$ssh_port_default" = "1" ]; then
  sshport=$(random 21000 29000)
else
  sshport=$oldsshport
fi

sed -i "/^\(\s\|#\)*Port / c\Port $sshport" /etc/ssh/sshd_config
sed -i "/^\(\s\|#\)*X11Forwarding /c\X11Forwarding no" /etc/ssh/sshd_config
#sed -i '/^\s*PermitRootLogin/ c\PermitRootLogin no' /etc/ssh/sshd_config
sed -i '/^\s*PasswordAuthentication no/ c\#PasswordAuthentication no' /etc/ssh/sshd_config

echo >> /etc/ssh/sshd_config
grep -Pq "^[#\s]*UsePAM" /etc/ssh/sshd_config && sed -i '/^\(\s\|#\)*UsePAM/ c\UsePAM yes' /etc/ssh/sshd_config || echo "UsePAM yes" >> /etc/ssh/sshd_config
grep -Pq "^[#\s]*UseDNS" /etc/ssh/sshd_config && sed -i '/^\(\s\|#\)*UseDNS/ c\UseDNS no' /etc/ssh/sshd_config || echo "UseDNS no" >> /etc/ssh/sshd_config

if [ -z "$(grep sshuser /etc/group)" ]; then
groupadd sshuser
fi

allowlist=$(grep ^AllowUsers /etc/ssh/sshd_config)
if ! [ -z "$allowlist" ]; then
  for ssh_user in $allowlist
    do
      if   [ ! "$ssh_user" = "AllowUsers" ] && [ "$(groups $ssh_user 2> /dev/null | grep -E ' sudo(\s|$)')" = "" ]; then
        adduser $ssh_user sshuser
      fi
    done
  sed -i "/$allowlist/ d" /etc/ssh/sshd_config
fi
#grep "AllowGroups sudo sshuser" /etc/ssh/sshd_config > /dev/null || echo "AllowGroups sudo sshuser" >> /etc/ssh/sshd_config

service ssh restart 1>> $logfile
sshport=$(grep 'Port ' /etc/ssh/sshd_config | sed 's/[^0-9]*//g')
echo "SSH port set to $sshport"

###############################
### SSL CERTIFICATES ###
###############################

# calls the script rtsslcert to generate the ssl certificated for vsftpd and nginx
rtsslcert -d

###############################
### INSTALL FTP ###
###############################

if [[ $ftp_port_default = 0 ]]; then
    ftpport=21
else
    ftpport=$(random 41005 48995)
fi

if [ $(dpkg-query -W -f='${Status}' "vsftpd" 2>/dev/null | grep -c "ok installed") -eq 0 ]; then
  echo "Installing vsftpd" | tee -a $logfile
  apt-get -y install vsftpd >> $logfile 2>&1
fi

sed -i '/^\(\s\|#\)*anonymous_enable/ c\anonymous_enable=NO' /etc/vsftpd.conf
sed -i '/^\(\s\|#\)*local_enable/ c\local_enable=YES' /etc/vsftpd.conf
sed -i '/^\(\s\|#\)*write_enable/ c\write_enable=YES' /etc/vsftpd.conf
sed -i '/^\(\s\|#\)*local_umask/ c\local_umask=022' /etc/vsftpd.conf
sed -i '/^\(\s\|#\)*listen=/ c\listen=YES' /etc/vsftpd.conf
sed -i '/^\(\s\|#\)*rsa_private_key_file/ c\rsa_private_key_file=\/etc\/ssl\/private\/ruweb\.key' /etc/vsftpd.conf
sed -i '/^\(\s\|#\)*rsa_cert_file/ c\rsa_cert_file=\/etc\/ssl\/ruweb\.crt' /etc/vsftpd.conf

sed -i 's/^\s*listen_ipv6/#listen_ipv6/g' /etc/vsftpd.conf

grep ^listen_port /etc/vsftpd.conf > /dev/null || echo "listen_port=$ftpport" >> /etc/vsftpd.conf

if [[ $LANG =~ .*[Uu][Tt][Ff]-?8.* ]]; then
  grep -Pq "utf8_filesystem=" /etc/vsftpd.conf && sed -i '/^\(\s\|#\)*utf8_filesystem=/ c\utf8_filesystem=YES' /etc/vsftpd.conf ||  echo "utf8_filesystem=YES" >> /etc/vsftpd.conf
fi

grep -Pq "use_sendfile=" /etc/vsftpd.conf && sed -i '/^\(\s\|#\)*use_sendfile=/ c\use_sendfile=NO' /etc/vsftpd.conf ||  echo "use_sendfile=NO" >> /etc/vsftpd.conf
grep -Pq "^\s*ssl_enable" /etc/vsftpd.conf && sed -i '/^\s*ssl_enable/ c\ssl_enable=YES' /etc/vsftpd.conf ||  echo "ssl_enable=YES" >> /etc/vsftpd.conf
grep -Pq "^\s*chroot_local_user" /etc/vsftpd.conf &&  sed -i '/^\s*chroot_local_user/ c\chroot_local_user=YES' /etc/vsftpd.conf || echo "chroot_local_user=YES" >> /etc/vsftpd.conf
grep -Pq "^\s*allow_writeable_chroot" /etc/vsftpd.conf &&  sed -i '/^\s*allow_writeable_chroot/ c\allow_writeable_chroot=YES' /etc/vsftpd.conf || echo "allow_writeable_chroot=YES" >> /etc/vsftpd.conf
grep -Pq "^\s*allow_anon_ssl" /etc/vsftpd.conf && sed -i '/^\s*allow_anon_ssl/ c\allow_anon_ssl=NO' /etc/vsftpd.conf || echo "allow_anon_ssl=NO" >> /etc/vsftpd.conf
grep -Pq "^\s*force_local_data_ssl" /etc/vsftpd.conf && sed -i '/^\s*force_local_data_ssl/ c\force_local_data_ssl=YES' /etc/vsftpd.conf || echo "force_local_data_ssl=YES" >> /etc/vsftpd.conf
grep -Pq "^\s*force_local_logins_ssl" /etc/vsftpd.conf && sed -i '/^\s*force_local_logins_ssl/ c\force_local_logins_ssl=YES' /etc/vsftpd.conf || echo "force_local_logins_ssl=YES" >> /etc/vsftpd.conf
grep -Pq "^\s*ssl_sslv2" /etc/vsftpd.conf &&  sed -i '/^\s*ssl_sslv2/ c\ssl_sslv2=YES' /etc/vsftpd.conf || echo "ssl_sslv2=YES" >> /etc/vsftpd.conf
grep -Pq "^\s*ssl_sslv3" /etc/vsftpd.conf &&  sed -i '/^\s*ssl_sslv3/ c\ssl_sslv3=YES' /etc/vsftpd.conf || echo "ssl_sslv3=YES" >> /etc/vsftpd.conf
grep -Pq "^\s*ssl_tlsv1" /etc/vsftpd.conf &&  sed -i '/^\s*ssl_tlsv1/ c\ssl_tlsv1=YES' /etc/vsftpd.conf || echo "ssl_tlsv1=YES" >> /etc/vsftpd.conf
grep -Pq "^\s*require_ssl_reuse" /etc/vsftpd.conf &&  sed -i '/^\s*require_ssl_reuse/ c\require_ssl_reuse=NO' /etc/vsftpd.conf || echo "require_ssl_reuse=NO" >> /etc/vsftpd.conf
grep -Pq "^\s*ssl_ciphers" /etc/vsftpd.conf &&  sed -i '/^\s*ssl_ciphers/ c\ssl_ciphers=HIGH' /etc/vsftpd.conf || echo "ssl_ciphers=HIGH" >> /etc/vsftpd.conf

service vsftpd restart 1>> $logfile

ftpport=$(grep 'listen_port=' /etc/vsftpd.conf | sed 's/[^0-9]*//g')
echo "FTP port set to $ftpport"

###############################
### INSTALL NGINX ###
###############################

cd $home

if [ -f "/etc/apache2/ports.conf" ]; then
  echo "Detected apache2. Changing apache2 port to 81 in /etc/apache2/ports.conf" | tee -a $logfile
  sed -i "s/Listen 80/Listen 81/g" /etc/apache2/ports.conf
  service apache2 stop >> $logfile 2>&1
fi

echo "Installing nginx" | tee -a $logfile

if [ $passflag != 2 ]; then
  if [ -f $passfile ]; then
    htpasswd -b $passfile $user $webpass >> $logfile 2>&1
  else
    htpasswd -c -b $passfile $user $webpass >> $logfile 2>&1
  fi
fi

chown www-data:www-data $passfile
chmod 640 $passfile

sed -i "s/user www-data;/user www-data www-data;/g" /etc/nginx/nginx.conf
sed -i "s/worker_processes 4;/worker_processes 1;/g" /etc/nginx/nginx.conf
sed -i "s/pid \/run\/nginx\.pid;/pid \/var\/run\/nginx\.pid;/g" /etc/nginx/nginx.conf
sed -i "s/# server_tokens off;/server_tokens off;/g" /etc/nginx/nginx.conf
sed -i "s/access_log \/var\/log\/nginx\/access\.log;/access_log off;/g" /etc/nginx/nginx.conf
sed -i "s/error\.log;/error\.log crit;/g" /etc/nginx/nginx.conf
grep client_max_body_size /etc/nginx/nginx.conf > /dev/null 2>&1 || sed -i "/server_tokens off;/ a\        client_max_body_size 40m;\n" /etc/nginx/nginx.conf
sed -i "/upload_max_filesize/ c\upload_max_filesize = 40M" $phploc/fpm/php.ini
sed -i '/^;\?listen.owner/ c\listen.owner = www-data' $phploc/fpm/pool.d/www.conf
sed -i '/^;\?listen.group/ c\listen.group = www-data' $phploc/fpm/pool.d/www.conf
sed -i '/^;\?listen.mode/ c\listen.mode = 0660' $phploc/fpm/pool.d/www.conf

mkdir -p /var/www
if [ -d "/usr/share/nginx/www" ]; then
  cp /usr/share/nginx/www/* /var/www
elif [ -d "/usr/share/nginx/html" ]; then
  cp /usr/share/nginx/html/* /var/www
fi

mv -n /etc/nginx/sites-available/default /etc/nginx/sites-available/default.original

cp -f /etc/rtinst/conf/nginxsite /etc/nginx/sites-available/default
cp -f /etc/rtinst/conf/nginxsitedl /etc/nginx/sites-available/dload-loc

echo "location ~ \.php$ {" > /etc/nginx/conf.d/php
echo "          fastcgi_split_path_info ^(.+\.php)(/.+)$;" >> /etc/nginx/conf.d/php

if [ "$phpver" = "php5" ]; then
  echo "          fastcgi_pass unix:/var/run/php5-fpm.sock;" >> /etc/nginx/conf.d/php
else
  echo "          fastcgi_pass unix:/var/run/php/$phpver-fpm.sock;" >> /etc/nginx/conf.d/php
fi

echo "          fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;" >> /etc/nginx/conf.d/php
echo "          fastcgi_index index.php;" >> /etc/nginx/conf.d/php
echo "          include fastcgi_params;" >> /etc/nginx/conf.d/php
echo "}" >> /etc/nginx/conf.d/php

echo "location ~* \.(jpg|jpeg|gif|css|png|js|woff|ttf|svg|eot)$ {" > /etc/nginx/conf.d/cache
echo "        expires 30d;" >> /etc/nginx/conf.d/cache
echo "}" >> /etc/nginx/conf.d/cache

# set up default proxy settings
echo 'proxy_redirect off;' > /etc/nginx/conf.d/proxy
echo 'proxy_set_header Host $host;' >> /etc/nginx/conf.d/proxy
echo 'proxy_set_header X-Real-IP $remote_addr;' >> /etc/nginx/conf.d/proxy
echo 'proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;' >> /etc/nginx/conf.d/proxy
echo 'proxy_cache off;' >> /etc/nginx/conf.d/proxy
echo 'proxy_buffering off;' >> /etc/nginx/conf.d/proxy

# clients reverse proxy
mkdir -p /etc/nginx/snippets
cp -f /etc/rtinst/conf/deluge.conf       /etc/nginx/snippets/deluge.conf
cp -f /etc/rtinst/conf/rutorrent.conf    /etc/nginx/snippets/rutorrent.conf
cp -f /etc/rtinst/conf/qbittorrent.conf   /etc/nginx/snippets/qbittorrent.conf
cp -f /etc/rtinst/conf/transmission.conf /etc/nginx/snippets/transmission.conf
cp -f /etc/rtinst/conf/flood.conf /etc/nginx/snippets/flood.conf
cp -f /etc/rtinst/conf/flexget.conf /etc/nginx/snippets/flexget.conf

service nginx restart && service $phpver-fpm restart

if [ $dlflag = 0 ]; then
  rtdload enable
fi

###############################
### INSTALL RTORRENT ###
###############################

if [ $skip_rt = 1 ]; then
  if [ -z $rtorrentrel ]; then
    rtorrentrel='latest'
  fi
  export home
  # call the script rtupdate to install lib/rtorrent
  if [ $enable_ipv6 = 1 ]; then
    rtupdate "$rtorrentrel" || early_exit
  else
    rtupdate -i "$rtorrentrel" || early_exit
  fi
  export -n home
else
  echo "skiping rtorrent installation" | tee -a $logfile
fi

echo "Configuring rtorrent" | tee -a $logfile
cd $home

mkdir -p rtorrent/.session
mkdir -p rtorrent/download
mkdir -p rtorrent/watch

cp -f /etc/rtinst/conf/rtorrent.rc $home/.rtorrent.rc
sed -i "s|<user home>|${home}|g" $home/.rtorrent.rc
sed -i "s/<user name>/$user/g" $home/.rtorrent.rc

###############################
### INSTALL RUTORRENT ###
###############################

mkdir -p /var/www
cd /var/www

echo -n "RuTorrent: "; check_url $ru_url && echo "OK" || { echo "FAIL"; early_exit; }

if [ -d "/var/www/rutorrent" ]; then
  rm -r /var/www/rutorrent
fi

if [ $rudevflag = 1 ]; then
   rurelease=$(git ls-remote -t https://github.com/Novik/ruTorrent v\* | cut -d/ -f3 | sort -V | tail -1)
fi

echo "Installing Rutorrent ($rurelease)" | tee -a $logfile
wget -q https://github.com/Novik/ruTorrent/archive/$rurelease.tar.gz | tee -a $logfile
tar -xzf $rurelease.tar.gz
mv $(tar -tzf $rurelease.tar.gz | head -1) rutorrent
rm $rurelease.tar.gz

echo "Configuring Rutorrent" | tee -a $logfile
rm rutorrent/conf/config.php
cp -f /etc/rtinst/conf/ru.config /var/www/rutorrent/conf/config.php
mkdir -p /var/www/rutorrent/conf/users/$user/plugins

echo "<?php" > /var/www/rutorrent/conf/users/$user/config.php
echo >> /var/www/rutorrent/conf/users/$user/config.php
echo "\$homeDirectory = \"$home\";" >> /var/www/rutorrent/conf/users/$user/config.php
echo "\$topDirectory = \"$home\";" >> /var/www/rutorrent/conf/users/$user/config.php
echo "\$scgi_port = 5000;" >> /var/www/rutorrent/conf/users/$user/config.php
echo "\$XMLRPCMountPoint = \"/RPC2\";" >> /var/www/rutorrent/conf/users/$user/config.php
echo "\$SCGIServerTimeout = 60;" >> /var/www/rutorrent/conf/users/$user/config.php
echo >> /var/www/rutorrent/conf/users/$user/config.php
echo "?>" >> /var/www/rutorrent/conf/users/$user/config.php

cp -f /etc/rtinst/conf/ru.ini /var/www/rutorrent/conf/plugins.ini
[[ ! ` grep m2ts /var/www/rutorrent/plugins/screenshots/conf.php ` ]] && sed -i "s/\"mkv\"/\"mkv\",\"m2ts\"/g" /var/www/rutorrent/plugins/screenshots/conf.php

if [ $osname = "Raspbian" ]; then
  sed -i '/\[screenshots\]/,+1d' /var/www/rutorrent/conf/plugins.ini
  sed -i '/\[unpack\]/,+1d' /var/www/rutorrent/conf/plugins.ini
  echo '[screenshots]' >> /var/www/rutorrent/conf/plugins.ini
  echo 'enabled = no' >> /var/www/rutorrent/conf/plugins.ini
  echo '[unpack]' >> /var/www/rutorrent/conf/plugins.ini
  echo 'enabled = no' >> /var/www/rutorrent/conf/plugins.ini
fi

# set min rss interval to 0.1 minutes
sed -i "s/2/0.1/" /var/www/rutorrent/plugins/rss/conf.php

###############################
### INSTALL AUTODL-IRSSI ###
###############################

echo "Installing autodl-irssi" | tee -a $logfile
adlport=$(random 36001 36100)
adlpass=$(genpasswd $(random 12 16))

mkdir -p $home/.irssi/scripts/autorun
cd $home/.irssi/scripts
curl -sL http://git.io/vlcND | grep -Po '(?<="browser_download_url": ")(.*-v[\d.]+.zip)' | xargs wget --quiet -O autodl-irssi.zip
unzip -qq -o autodl-irssi.zip | tee -a $logfile
rm autodl-irssi.zip
cp autodl-irssi.pl autorun/
mkdir -p $home/.autodl

cd /var/www/rutorrent/plugins
git clone -q https://github.com/autodl-community/autodl-rutorrent.git autodl-irssi | tee -a $home/rtinst.info

mkdir /var/www/rutorrent/conf/users/$user/plugins/autodl-irssi

touch /var/www/rutorrent/conf/users/$user/plugins/autodl-irssi/conf.php

echo "<?php" > /var/www/rutorrent/conf/users/$user/plugins/autodl-irssi/conf.php
echo >> /var/www/rutorrent/conf/users/$user/plugins/autodl-irssi/conf.php
echo "\$autodlPort = $adlport;" >> /var/www/rutorrent/conf/users/$user/plugins/autodl-irssi/conf.php
echo "\$autodlPassword = \"$adlpass\";" >> /var/www/rutorrent/conf/users/$user/plugins/autodl-irssi/conf.php
echo >> /var/www/rutorrent/conf/users/$user/plugins/autodl-irssi/conf.php
echo "?>" >> /var/www/rutorrent/conf/users/$user/plugins/autodl-irssi/conf.php

cd $home/.autodl
rm -f autodl2.cfg

if [ -f "autodl.cfg" ]; then
  if (grep -sq gui-server-port autodl.cfg) && (grep -sq gui-server-password autodl.cfg); then
    sed -i "/gui-server-port/ c\gui-server-port = $adlport" autodl.cfg
    sed -i "/gui-server-password/ c\gui-server-password = $adlpass" autodl.cfg
  else
    sed -i '/gui-server-port/ d' autodl.cfg
    sed -i '/gui-server-password/ d' autodl.cfg
    echo >> autodl.cfg
    sed -i "1s/^/[options]\ngui-server-port = $adlport\ngui-server-password = $adlpass\n/" autodl.cfg
  fi
else
  echo "[options]" > autodl.cfg
  echo "gui-server-port = $adlport" >> autodl.cfg
  echo "gui-server-password = $adlpass" >> autodl.cfg
fi

# Fix AutoDL-Irssi issues on Ubuntu 16.04
apt-get install -y php-xml >> $logfile 2>&1


###############################
### Aniverse Mod ###
###############################

# 我也忘记是干嘛用的了
apt-get install -y --allow-unauthenticated libncurses5-dev libncursesw5-dev >> $logfile 2>&1

# Used for logging
mkdir -p /etc/inexistence/01.Log
touch /etc/inexistence/01.Log/{rutorrent_errors.log,rtorrent.log}
chmod -R 666 /etc/inexistence/01.Log/{rutorrent_errors.log,rtorrent.log}

###### ruTorrent themes #######
echo "Installing ruTorrent themes" | tee -a $logfile
cd /var/www/rutorrent/plugins/theme/themes
svn co -q https://github.com/ArtyumX/ruTorrent-Themes/trunk/MaterialDesign >> /dev/null 2>&1
svn co -q https://github.com/ArtyumX/ruTorrent-Themes/trunk/club-QuickBox >> /dev/null 2>&1

#### ruTorrent filemanager ####
echo "Installing ruTorrent third party plugins" | tee -a $logfile
cd /var/www/rutorrent/plugins
apt-get -y install zip >> $logfile 2>&1

svn co -q https://github.com/nelu/rutorrent-thirdparty-plugins/trunk/filemanager
cat > /var/www/rutorrent/plugins/filemanager/conf.php << EOF
<?php

\$fm['tempdir'] = '/tmp';                // path were to store temporary data ; must be writable
\$fm['mkdperm'] = 755;           // default permission to set to new created directories

// set with fullpath to binary or leave empty
\$pathToExternals['rar'] = '$(which rar)';
\$pathToExternals['zip'] = '$(which zip)';
\$pathToExternals['unzip'] = '$(which unzip)';
\$pathToExternals['tar'] = '$(which tar)';
\$pathToExternals['bzip2'] = '$(which bzip2)';

// archive mangling, see archiver man page before editing

\$fm['archive']['types'] = array('rar', 'zip', 'tar', 'gzip', 'bzip2');

\$fm['archive']['compress'][0] = range(0, 5);
\$fm['archive']['compress'][1] = array('-0', '-1', '-9');
\$fm['archive']['compress'][2] = \$fm['archive']['compress'][3] = \$fm['archive']['compress'][4] = array(0);

?>
EOF
chmod -R 755 /var/www/rutorrent/plugins/filemanager/scripts

###### ruTorrent plugins ######

#svn co -q https://github.com/nelu/rutorrent-thirdparty-plugins/trunk/fileupload
#apt-get -y install plowshare >> $logfile 2>&1
#mkdir -p /var/www/rutorrent/conf/users/"${user}"/plugins/fileupload
#chmod 775 /var/www/rutorrent/plugins/fileupload/scripts/upload
#cp /var/www/rutorrent/plugins/fileupload/conf.php /var/www/rutorrent/conf/users/"${user}"/plugins/fileupload/conf.php

svn co -q https://github.com/nelu/rutorrent-thirdparty-plugins/trunk/fileshare
ln -s /var/www/rutorrent/plugins/fileshare/share.php /var/www/share.php
sed -i "s|'http://mydomain.com/share.php';|\$_SERVER['HTTP_HOST'] . '/share.php';|g" /var/www/rutorrent/plugins/fileshare/conf.php

svn co -q https://github.com/nelu/rutorrent-thirdparty-plugins/trunk/mediastream
ln -s /var/www/rutorrent/plugins/mediastream/view.php /var/www/mediastream.php

git clone https://github.com/xombiemp/rutorrentMobile mobile >> $logfile 2>&1

############ h5ai #############
echo "Configuring h5ai" | tee -a $logfile
apt-get install -y imagemagick vim sox libsox-fmt-mp3 >> $logfile 2>&1
mkdir -p /var/www/h5ai && cd /var/www/h5ai
wget --no-check-certificate -t1 --timeout=7 https://release.larsjung.de/h5ai/h5ai-0.29.0.zip >> $logfile 2>&1
unzip -o h5ai-0.29.0.zip >/dev/null
rm -rf h5ai-0.29.0.zip # index.html
chmod 755 -R _h5ai/private/cache _h5ai/public/cache
service nginx restart >> $logfile 2>&1
ln -s /home/${user}/rtorrent/download /var/www/h5ai/rtorrent


###############################
### FINAL TASKS ###
###############################

# set permissions
echo "Setting permissions, Starting services" | tee -a $logfile
chown -R www-data:www-data /var/www
chown -R $user:$user $home

if [ $dlflag = 0 ]; then
  find $home -type d -print0 | xargs -0 chmod 755
fi

cd $home

#allows users to change their rutorrent passwords
if [ -z "$(grep "ALL ALL = NOPASSWD: /usr/local/bin/rtsetpass" /etc/sudoers)" ]; then
  echo "ALL ALL = NOPASSWD: /usr/local/bin/rtsetpass" | (EDITOR="tee -a" visudo)  > /dev/null 2>&1
fi

# restart rtorrent and irssi
su $user -c '/usr/local/bin/rt restart'
su $user -c '/usr/local/bin/rt -i restart'

# set up crontab entries
if [ -z "$(crontab -u $user -l | grep "$cronline1")" ]; then
    (crontab -u $user -l; echo "$cronline1" ) | crontab -u $user - >> $logfile 2>&1
fi

if [ -z  "$(crontab -u $user -l | grep "\*/10 \* \* \* \* /usr/local/bin/rtcheck irssi rtorrent")" ]; then
    (crontab -u $user -l; echo "$cronline2" ) | crontab -u $user - >> $logfile 2>&1
fi

# add aditional users if any
if [ $rut_add_users = 0 ]; then
  for rut_user in $rut_user_list; do
    echo "Adding $rut_user"
    rtadduser -n -u $rut_user >> $logfile 2>&1
  done
fi

###############################
### WRITE RTINST.INFO ###
###############################

ftp_current=$(apt-cache policy vsftpd | grep -o Installed.* | cut -d ' ' -f2)
rt_current=$(rtorrent -h | grep -om 1 "[0-9]\{1,2\}\.[0-9]\{1,2\}\.[0-9]\{1,2\}")
ru_current=$(grep -m 1 version: /var/www/rutorrent/js/webui.js | cut -d \" -f2)

echo
echo
echo "Summary of Installation (Important Information, please read" | tee $home/rtinst.info

echo | tee $home/rtinst.info

echo "SSH Configured" | tee -a $home/rtinst.info
echo "   SSH port set to $sshport" | tee -a $home/rtinst.info
# echo "   root login directly from SSH disabled"
# echo "   login with $user and switch to root using: sudo su"

echo | tee -a $home/rtinst.info

echo "FTP Server"  | tee -a $home/rtinst.info
if installed vsftpd; then
  echo "   vsftpd $ftp_current installed" | tee -a $home/rtinst.info
  echo "   ftp port set to $ftpport" | tee -a $home/rtinst.info
  echo "   ftp client should be set to explicit ftp over tls using port $ftpport" | tee -a $home/rtinst.info
else
  echo "   vsftpd is not installed" | tee -a $home/rtinst.info
fi

echo | tee -a $home/rtinst.info

echo "rtorrent torrent client" | tee -a $home/rtinst.info
if installed rtorrent; then
  echo "   rtorrent $rt_current installed" | tee -a $home/rtinst.info
  echo "   crontab entries made. rtorrent and irssi will start on boot for $user" | tee -a $home/rtinst.info
else
  echo "   rtorrent was not installed" | tee -a $home/rtinst.info
fi

echo | tee -a $home/rtinst.info

echo "RuTorrent Web GUI" | tee -a $home/rtinst.info
if [ -z $ru_current ]; then
  echo "   RuTorrent was not installed" | tee -a $home/rtinst.info
else
  echo "   RuTorrent $ru_current installed" | tee -a $home/rtinst.info
  echo "   rutorrent can be accessed at https://$serverip/rutorrent" | tee -a $home/rtinst.info
  if [ $passflag = 1 ]; then
    echo "   rutorrent password set to $webpass" | tee -a $home/rtinst.info
  elif [ $passflag = 2 ]; then
    echo "   rutorrent password has not been changed" | tee -a $home/rtinst.info
  else
    echo "   rutorrent password as set by user" | tee -a $home/rtinst.info
  fi
  echo "   to change rutorrent password enter: rtpass" | tee -a $home/rtinst.info
  echo | tee -a $home/rtinst.info
  echo "   Access https downloads at https://$serverip/h5ai" | tee -a $home/rtinst.info
fi

echo | tee -a $home/rtinst.info

echo "IMPORTANT: SSH Port set to $sshport" | tee -a $home/rtinst.info
echo "IMPORTANT: SSH Port set to $sshport"
echo "IMPORTANT: SSH Port set to $sshport"
echo "Please ensure you can login BEFORE closing this session"
echo
echo "The above information is stored in rtinst.info in your home directory."
echo "To see contents enter: cat $home/rtinst.info"
echo
echo "To install webmin enter: sudo rtwebmin"
echo
echo "SCROLL UP IF NEEDED TO READ ALL THE SUMMARY INFO"
echo "PLEASE REBOOT YOUR SYSTEM ONCE YOU HAVE NOTED THE ABOVE INFORMATION"
echo | tee -a $home/rtinst.info
echo "Thank You for choosing rtinst" | tee -a $home/rtinst.info
echo
chown $user rtinst.info
